<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo.jpg?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo.jpg?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="ASP.NET Core,MVC,中间件,管道," />










<meta name="keywords" content="ASP.NET Core,MVC,中间件,管道">
<meta property="og:type" content="article">
<meta property="og:title" content="ASP.NET Core中间件的注册和管道的构建（2）---- 用UseMiddleware扩展方法注册中间件类">
<meta property="og:url" content="http://durow.vip/2016/08/08/NetCore/ASP-NET-Core中间件的注册和管道的构建（2）-用UseMiddleware扩展方法注册中间件类/index.html">
<meta property="og:site_name" content="Durowの隅">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0804/201608040000.jpg">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080101.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080102.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080201.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080202.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080203.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080204.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080205.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080206.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080401.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080402.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080403.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080404.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080405.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/0808/201608080406.png">
<meta property="og:updated_time" content="2018-03-23T05:52:35.752Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ASP.NET Core中间件的注册和管道的构建（2）---- 用UseMiddleware扩展方法注册中间件类">
<meta name="twitter:image" content="http://durow.gitee.io/source/images/2016/0804/201608040000.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"always","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://durow.vip/2016/08/08/NetCore/ASP-NET-Core中间件的注册和管道的构建（2）-用UseMiddleware扩展方法注册中间件类/"/>





  <title>ASP.NET Core中间件的注册和管道的构建（2）---- 用UseMiddleware扩展方法注册中间件类 | Durowの隅</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b5605a7aa8d230851edcda67de588833";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Durowの隅</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">forever love, forever dream</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="st-search-show-outputs">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <form class="site-search-form">
  <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>

<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install', 'jv23s59-xwQTfQjP6xPi','2.0.0');
</script>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://durow.vip/2016/08/08/NetCore/ASP-NET-Core中间件的注册和管道的构建（2）-用UseMiddleware扩展方法注册中间件类/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="durow">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Durowの隅">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ASP.NET Core中间件的注册和管道的构建（2）---- 用UseMiddleware扩展方法注册中间件类</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-08-08T09:59:00+08:00">
                2016-08-08
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/NET-Core/" itemprop="url" rel="index">
                    <span itemprop="name">.NET Core</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/NET-Core/MVC/" itemprop="url" rel="index">
                    <span itemprop="name">MVC</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2016/08/08/NetCore/ASP-NET-Core中间件的注册和管道的构建（2）-用UseMiddleware扩展方法注册中间件类/" class="leancloud_visitors" data-flag-title="ASP.NET Core中间件的注册和管道的构建（2）---- 用UseMiddleware扩展方法注册中间件类">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p><img src="http://durow.gitee.io/source/images/2016/0804/201608040000.jpg" alt="Pipline"></p>
<a id="more"></a>
<h2 id="0x00-为什么要引入扩展方法"><a href="#0x00-为什么要引入扩展方法" class="headerlink" title="0x00 为什么要引入扩展方法"></a>0x00 为什么要引入扩展方法</h2><p>有的中间件功能比较简单，有的则比较复杂，并且依赖其它组件。除了直接用ApplicationBuilder的Use()方法注册中间件外，还可以使用ApplicationBuilder的扩展方法UseMiddleware()注册中间件。这种情况下可以注册类型，这个方法会通过反射解析这个类型，并把它包装成Func&lt;ReuqestDelegate,RequestDelegate&gt;然后调用Use()方法注册。</p>
<p>遇到这种情况一般直觉上是通过继承一个抽象类并实现其中的方法在写一个中间件。不过.NET Core不是这么做的。中间件类使用约定而不是继承来进行约束。这里说的约定就是约定原本的意思，例如约定好了中间件类中必须包含一个叫Invoke的方法，叫别的就不行，有重载也不行。因为中间件类没有任何继承上的约束，在注册过程中就是通过反射去寻找名字为Invoke的方法，然后把它包装成RequestDelegate的。这篇文章就是要说一下写一个中间件类都有哪些约定以及中间件类的注册。</p>
<h2 id="0x01-一个最简单的例子"><a href="#0x01-一个最简单的例子" class="headerlink" title="0x01 一个最简单的例子"></a>0x01 一个最简单的例子</h2><p>先看一个中间件类的最简单的例子：</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080101.png" alt="Use"></p>
<p>上一篇文章中说过了，中间件本质就是一个方法，这个方法接收一个HttpContext参数，返回Task。在上面这个中间件类中Invoke就是这个方法。为了能够调用下一个中间件，当前中间件还需要保存下一个中间件的引用。这个引用是通过构造函数传进来的，如果当前中间件不需要调用后面中间件的话，这个引用完全可以不保存。如果要注册这个中间件，我们可以这样做：</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080102.png" alt="Use"></p>
<p>但如果我们这个中间件比较复杂，依赖很多其他模块，那么我们在注册的时候需要构造依赖模块的实例，并在中间件类的构造函数中把这些依赖传进去。这加强了中间件和依赖模块之间的耦合度。为了能减少这种耦合，同时享受到依赖注入带来的便利，提供了UseMiddleware<t>扩展方法来注册中间件类T。</t></p>
<p>UseMiddleware扩展方法会找到上面中间件类中的Invoke方法，创建上面类的实例，在创建实例时遇到需要注入的类型会尝试注入，然后把Invoke方法包装为ReuqestDelegate，进而包装为Func&lt;RequestDelegate,RequestDelegate&gt;，然后通过ApplicatonBuilder的Use方法（上篇文章讲过了）注册到IList&lt;Func&lt;RequestDelegaet,RequestDelegate&gt;中。</p>
<p>从上面的SimpleMiddleware我们可以看到这个类没有任何显示的继承关系，那么我们在写一个中间件类时需要注意哪些约束呢？我们只要看一下UseMiddleware注册中间件的过程就明白了。下面是对UseMiddleware()方法的分析，对代码分析不感兴趣的可以跳过直接看后面的结论和测试。</p>
<h2 id="0x02-扩展方法注册中间件类的过程"><a href="#0x02-扩展方法注册中间件类的过程" class="headerlink" title="0x02 扩展方法注册中间件类的过程"></a>0x02 扩展方法注册中间件类的过程</h2><p>使用UseMiddleware&lt;T&gt;扩展方法注册中间件类T主要包含以下几个关键步骤：</p>
<h3 id="1-找到中间件类的Invoke方法"><a href="#1-找到中间件类的Invoke方法" class="headerlink" title="1.找到中间件类的Invoke方法"></a>1.找到中间件类的Invoke方法</h3><p>UseMiddleware方法会通过反射获取注册的中间件类的所有public且非static的方法列表，然后从其中找出名字叫Invoke的方法，确认Invoke方法没有重载，确认Invoke方法返回Task，确认Invoke方法第一个参数是HttpContext，最后这两个检查是为了能把Invoke方法包装为RequestDelegate。</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080201.png" alt="Use"></p>
<h3 id="2-选取最佳构造函数"><a href="#2-选取最佳构造函数" class="headerlink" title="2.选取最佳构造函数"></a>2.选取最佳构造函数</h3><p>把下一个中间件的引用next插入到从UseMiddleware传入的参数列表的第一个，作为给定的参数列表。</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080202.png" alt="Use"></p>
<p>然后获取中间件类的所有构造函数，从给定的参数列表中依次取出参数，和构造函数的参数进行类型匹配，匹配最多的构造函数选为最佳构造函数。匹配相同的以代码中排在前面的构造函数为准（这其中省略了很多匹配最佳构造函数的细节，感兴趣的可以自行查看代码）。</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080203.png" alt="Use"></p>
<p>值得注意的是如果存在给定的参数列表中存在某个参数P，在当前构造函数参数列表中找不到与之匹配的类型，那么这个构造函数不能作为最佳构造函数。也就是说选中的最佳构造函数的参数列表必须要是给定参数列表的超集。刚刚上面也说了，下一个中间件next被插入到了给定参数列表的第一个，因此选中的最佳构造函数参数中必须包含参数RequestDelegate。如果所有构造函数都不包含RequestDelegate，那么会抛出异常。</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080204.png" alt="Use"></p>
<h3 id="3-构造中间件类的实例"><a href="#3-构造中间件类的实例" class="headerlink" title="3.构造中间件类的实例"></a>3.构造中间件类的实例</h3><p>找到了最佳构造函数后，接下来就使用该构造函数构造中间件类的实例。对于构造函数中的所有参数，能够从给定的参数列表中找到类型匹配的，从给定的参数列表中获取参数。从参数列表中找不到的，则尝试从依赖注入容器中获取，依赖注入容器中也找不到的检查是不是有默认值，默认值也没有就抛出异常。</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080205.png" alt="Use"></p>
<h3 id="4-包装委托"><a href="#4-包装委托" class="headerlink" title="4.包装委托"></a>4.包装委托</h3><p>实例构造完成后，如果Invoke方法只有一个参数（HttpContext）会把这个实例的Invoke方法包装为RequestDelegate，进而包装为Func&lt;RequestDelegate,RequestDelegate&gt;然后使用Use方法注册。如果有多个参数，不符合RequestDelegate约束，则对Invoke进行二次包装以符合RequestDelegate。在二次包装中会尝试从依赖注入容器中获取Invoke参数中的依赖。</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080206.png" alt="Use"></p>
<h2 id="0x03一些结论"><a href="#0x03一些结论" class="headerlink" title="0x03一些结论"></a>0x03一些结论</h2><p>下面总结一下中间件类的一些约定，主要是基于对代码的理解，有错误或不全的地方请指正。</p>
<p>关于中间件的方法：</p>
<ul>
<li>1.中间件的方法必须叫Invoke，且为public，非static。</li>
<li>2.Invoke方法第一个参数必须是HttpContext类型。</li>
<li>3.Invoke方法必须返回Task。</li>
<li>4.Invoke方法可以有多个参数，除HttpContext外其它参数会尝试从依赖注入容器中获取。</li>
<li>5.Invoke方法不能有重载。</li>
</ul>
<p>关于构造函数：</p>
<ul>
<li>1.构造函数必须包含RequestDelegate参数，该参数传入的是下一个中间件。</li>
<li>2.构造函数参数中的RequestDelegate参数不是必须放在第一个，可以是任意位置。</li>
<li>3.构造函数可以有多个参数，参数会优先从给定的参数列表中找，其次会从依赖注入容器中获取，获取失败会尝试获取默认值，都失败会抛出异常。</li>
<li>4.构造函数可以有多个，届时会根据构造函数参数列表和给定的参数列表选择匹配度最高的一个。</li>
</ul>
<p>个人建议，真的仅仅是个人的一些建议：</p>
<ul>
<li>1.除及特殊情况外只保留一个构造函数，以省去多余的构造函数匹配检查。</li>
<li>2.在构造函数中注入所需依赖而不是Invoke中。</li>
<li>3.关于构造函数参数的顺序，把RequestDelegate放在第一个；之后是UseMiddleware方法中给出的参数，而且构造函数中参数顺序和给定参数列表中的顺序最好也相同；然后是需要注入的参数；最后是有默认值的参数。以上除了默认值参数必须放在最后外其余的顺序都不是必须的，但按照上面的顺序会比较清晰，而且能使实例创建的开销最小。</li>
<li>4.Invoke方法只保留一个HttpContext参数。这样可以省去对Invoke方法的二次包装。</li>
<li>5.进一步扩展ApplicationBuilder，创建语义更加明确的方法代替Use/UseMiddleware，例如UseMVC、UseStaticFiles。</li>
</ul>
<p>其中1中所说的及特殊的情况，我能想到的就是给UseMiddleware提供不同的参数列表，进而匹配到不同的构造函数创建实例。具体使用场景没有想到。</p>
<h2 id="0x04-测试"><a href="#0x04-测试" class="headerlink" title="0x04 测试"></a>0x04 测试</h2><p>上篇文章中我们写过一个记录后面所有中间件耗时的中间件。当时直接用Use方法注册的。现在我们把它写为一个中间件类，并且把计时功能写为一个StopWatch类，并添加到依赖注入容器中。</p>
<p>下面是计时器类的代码：</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080401.png" alt="Use"></p>
<p>下面是中间件类的代码</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080402.png" alt="Use"></p>
<p>下面是向依赖注入容器中添加StopWatch</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080403.png" alt="Use"></p>
<p>下面是使用UseMiddleware扩展方法添加TimeMiddleware中间件代码</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080404.png" alt="Use"></p>
<p>当然，也可以不把StopWatch添加到依赖注入容器中，而是在UserMiddleware方法中直接给出参数。</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080405.png" alt="Use"></p>
<p>如果既在依赖注入容器中添加了StopWatch，又在UseMiddleware注册时提供了StopWatch，那么按照参数匹配顺序最终使用的是注册时提供的StopWatch。</p>
<p>运行一下可以看到与上篇文章同样的效果。</p>
<p><img src="http://durow.gitee.io/source/images/2016/0808/201608080406.png" alt="Use"></p>
<h2 id="0x05-写在最后"><a href="#0x05-写在最后" class="headerlink" title="0x05 写在最后"></a>0x05 写在最后</h2><p>UseMiddleware方法使注册中间件变得容易，同事也减小了中间件和其它依赖模块间的耦合。不过不管哪种扩展方法，最终都是通过Use方法实现中间件的注册。下一篇文章将写一下注册中间件的其它扩展方法Map、MapWhen和Run。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果觉得有用请打赏一杯咖啡，谢谢 :P</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/WeChatPay.png" alt="durow 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/AliPay.jpg" alt="durow 支付宝"/>
        <p>支付宝</p>
      </div>
    

    
      <div id="bitcoin" style="display: inline-block">
        <img id="bitcoin_qr" src="/images/BitcoinPay.png" alt="durow 比特币"/>
        <p>比特币<br>地址:1433nFc4GmHj1gnXdhzA4T944WqSdBajuo</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    durow
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://durow.vip/2016/08/08/NetCore/ASP-NET-Core中间件的注册和管道的构建（2）-用UseMiddleware扩展方法注册中间件类/" title="ASP.NET Core中间件的注册和管道的构建（2）---- 用UseMiddleware扩展方法注册中间件类">http://durow.vip/2016/08/08/NetCore/ASP-NET-Core中间件的注册和管道的构建（2）-用UseMiddleware扩展方法注册中间件类/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/ASP-NET-Core/" rel="tag"># ASP.NET Core</a>
          
            <a href="/tags/MVC/" rel="tag"># MVC</a>
          
            <a href="/tags/中间件/" rel="tag"># 中间件</a>
          
            <a href="/tags/管道/" rel="tag"># 管道</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/08/04/NetCore/ASP-NET-Core中间件的注册和管道的构建（1）-注册和构建原理/" rel="next" title="ASP.NET Core中间件的注册和管道的构建（1）---- 注册和构建原理">
                <i class="fa fa-chevron-left"></i> ASP.NET Core中间件的注册和管道的构建（1）---- 注册和构建原理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/08/09/NetCore/ASP-NET-Core中间件的注册和管道的构建（3）-使用Map-MapWhen扩展方法/" rel="prev" title="ASP.NET Core中间件的注册和管道的构建（3）---- 使用Map/MapWhen扩展方法">
                ASP.NET Core中间件的注册和管道的构建（3）---- 使用Map/MapWhen扩展方法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=2159540" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTAyNi8xMTU2Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/logo.jpg"
                alt="durow" />
            
              <p class="site-author-name" itemprop="name">durow</p>
              <p class="site-description motion-element" itemprop="description">热爱生活 热爱学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">53</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="http://www.qq.com" target="_blank" title="16141860">
                      
                        <i class="fa fa-fw fa-qq"></i>16141860</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:durow@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/durow" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/durow" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://space.bilibili.com/13399420/" target="_blank" title="Bilibili">
                      
                        <i class="fa fa-fw fa-tv"></i>Bilibili</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.twitter.com/durow1984" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-heart"></i>
                好站推荐
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://cnblogs.com/" title="博客园" target="_blank">博客园</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#0x00-为什么要引入扩展方法"><span class="nav-number">1.</span> <span class="nav-text">0x00 为什么要引入扩展方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x01-一个最简单的例子"><span class="nav-number">2.</span> <span class="nav-text">0x01 一个最简单的例子</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x02-扩展方法注册中间件类的过程"><span class="nav-number">3.</span> <span class="nav-text">0x02 扩展方法注册中间件类的过程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-找到中间件类的Invoke方法"><span class="nav-number">3.1.</span> <span class="nav-text">1.找到中间件类的Invoke方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-选取最佳构造函数"><span class="nav-number">3.2.</span> <span class="nav-text">2.选取最佳构造函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-构造中间件类的实例"><span class="nav-number">3.3.</span> <span class="nav-text">3.构造中间件类的实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-包装委托"><span class="nav-number">3.4.</span> <span class="nav-text">4.包装委托</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x03一些结论"><span class="nav-number">4.</span> <span class="nav-text">0x03一些结论</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x04-测试"><span class="nav-number">5.</span> <span class="nav-text">0x04 测试</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x05-写在最后"><span class="nav-number">6.</span> <span class="nav-text">0x05 写在最后</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">durow</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">47.2k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>



  <div class="footer-custom">Hosted by <a target="_blank" href="https://coding.net/pages" style="font-weight:bold">Coding Pages</a></div>


        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("Ai37u86U95uCssl57jjMliaH-gzGzoHsz", "QeIwQbw9Ndwl2sh4uawjySJJ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "middleRight";
      
          pbOptions.networks = "Wechat,Weibo,Douban,QQZone,Evernote,Twitter";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
